package com.zhongshengnetwork.rightbe.lang.activity;

import android.Manifest;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
//import android.support.annotation.NonNull;
//import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.provider.Settings;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.MyLocationStyle;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.core.SuggestionCity;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.Constant.Constant;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.common.AppThemeUtils;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.PermissionUtils;
import com.zhongshengnetwork.rightbe.common.ScreenUtils;
import com.zhongshengnetwork.rightbe.common.TopBarView;
import com.zhongshengnetwork.rightbe.common.activity.AppBaseActivity;
import com.zhongshengnetwork.rightbe.common.callback.PermissionCallback;
import com.zhongshengnetwork.rightbe.common.customview.CustomDialog;
import com.zhongshengnetwork.rightbe.common.utils.ToastUtil;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import me.nereo.multi_image_selector.MultiImageSelector;

public class SearchLocationActivity extends AppBaseActivity implements LocationSource,
        AMapLocationListener,TopBarView.onTitleBarClickListener,PoiSearch.OnPoiSearchListener,AMap.OnMapScreenShotListener {
    private TopBarView topbar;
    private AMap aMap;
    private MapView mapView;
    private OnLocationChangedListener mListener;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;
    private RadioGroup mGPSModeGroup;

    //private TextView mLocationErrText;
    private static final int STROKE_COLOR = Color.argb(0, 0, 0, 0);//Color.argb(180, 3, 145, 255);
    private static final int FILL_COLOR = Color.argb(10, 0, 0, 180);

    private PoiSearch.Query query;// Poi查询条件类
    private PoiSearch poiSearch;
    private boolean isSearching = false;
    private boolean isTip = false;
    private List<PoiItem> mList;
    private ListView listview;
    private MyAdapter adapter;
    private String filePath = "";
    private EditText search;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_location);
        topbar = (TopBarView)findViewById(R.id.topbar);
        topbar.getRightView().setVisibility(View.GONE);
        topbar.setClickListener(this);
        search = (EditText) findViewById(R.id.et_search);
        search.addTextChangedListener(new Watcher(search));
        mapView = (MapView) findViewById(R.id.selectmap);
        mapView.onCreate(savedInstanceState);// 此方法必须重写
        mList = new ArrayList<PoiItem>();
        listview=(ListView) findViewById(R.id.selectmap_listview);
        adapter=new MyAdapter();
        listview.setAdapter(adapter);
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                hintKeyBoard();
                PoiItem poiItem = mList.get(position);
                Bundle bundle = new Bundle();
                bundle.putDouble(APIKey.longtitudeKey,poiItem.getLatLonPoint().getLongitude());
                bundle.putDouble(APIKey.latitudeKey,poiItem.getLatLonPoint().getLatitude());
                bundle.putString(APIKey.locationKey,poiItem.getTitle());
                //bundle.putString(APIKey.urlKey,filePath);
                bundle.putString(APIKey.provinceKey,CommonUtils.formatString(poiItem.getProvinceName()));
                bundle.putString(APIKey.cityKey,CommonUtils.formatString(poiItem.getCityName()));
                Intent intent = new Intent();
                intent.putExtras(bundle);
                setResult(RESULT_OK,intent);
                finish();
            }
        });

        LinearLayout line = (LinearLayout) findViewById(R.id.line);
        line.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());
        LinearLayout activity_search_location = (LinearLayout) findViewById(R.id.activity_search_location);
        activity_search_location.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
        listview.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());
        listview.setDivider(new ColorDrawable(AppThemeUtils.getInstance().getBackgroundColor()));
        listview.setDividerHeight(ScreenUtils.dip2px(SearchLocationActivity.this, 1));

        getPersimmions();
    }

    //定位权限
    private void getPersimmions() {
        PermissionUtils.isLocationNote(SearchLocationActivity.this, new PermissionCallback() {
            @Override
            public void onResult(boolean flag, boolean showAlert) {
                if (flag == true){
                    ////判断当前是否是6.0版本
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        ArrayList<String> permissions = new ArrayList<String>();
                        /***
                         * 定位权限为必须权限，用户如果禁止，则每次进入都会申请
                         */
                        // 定位精确位置
                        if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                            permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);

                        }
                        if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                            permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);

                        }
                        if (permissions.size() > 0) {
                            requestPermissions(permissions.toArray(new String[permissions.size()]), 10000);
                        } else {//****这里写自己的定位调用***/////
                            ///当权限都有时，开始定位
                            //CustomApplication.startLocation();
                            init();
                        }
                    } else {
                        //****这里写自己的定位调用***/////
                        ///低于6.0以下，开始定位
                        //CustomApplication.startLocation();
                        init();
                    }
                }
            }
        });

    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // 权限被用户同意，可以做你要做的事情了。
            init();
        } else {
            // 权限被用户拒绝了，可以提示用户,关闭界面等等。
            init();
        }
    }

    public void hintKeyBoard() {
        //拿到InputMethodManager
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        //如果window上view获取焦点 && view不为空
        if (imm.isActive() && getCurrentFocus() != null) {
            //拿到view的token 不为空
            if (getCurrentFocus().getWindowToken() != null) {
                //表示软键盘窗口总是隐藏，除非开始时以SHOW_FORCED显示。
                imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    /**
     * 点击了返回导航按钮
     */
    @Override
    public void onBackClick() {
        //Toast.makeText(LoginActivity.this, "你点击了左侧按钮", Toast.LENGTH_LONG).show();
        hintKeyBoard();
        finish();
    }

    /**
     * 点击了右边导航按钮
     */
    @Override
    public void onRightClick() {

    }

    private void doSearch(double longitude, double latitude, String cityCode){
        if (isSearching == true){
            return;
        }
        isSearching = true;
        query = new PoiSearch.Query("", "", CommonUtils.formatString(cityCode));
        //keyWord表示搜索字符串，
        //第二个参数表示POI搜索类型，二者选填其一，
        //POI搜索类型共分为以下20种：汽车服务|汽车销售|
        // 汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|医疗保健服务|
        //住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|交通设施服务|
        //金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施
        //cityCode表示POI搜索区域，可以是城市编码也可以是城市名称，也可以传空字符串，空字符串代表全国在全国范围内进行搜索
        query.setPageSize(20);// 设置每页最多返回多少条poiitem
        query.setPageNum(0);//设置查询页码
        poiSearch = new PoiSearch(this, query);
        poiSearch.setBound(new PoiSearch.SearchBound(new LatLonPoint(latitude,
                longitude), 1000));//设置周边搜索的中心点以及半径
        poiSearch.setOnPoiSearchListener(this);
        poiSearch.searchPOIAsyn();
    }

    @Override
    public void onPoiSearched(PoiResult result, int rCode) {
        System.out.print("返回：onPoiSearched\n");
        if (rCode == 1000) {
            if (result != null && result.getQuery() != null) {// 搜索poi的结果
                if (result.getQuery().equals(query)) {// 是否是同一条
                    // 取得搜索到的poiitems有多少页
                    List<PoiItem> poiItems = result.getPois();// 取得第一页的poiitem数据，页数从数字0开始
                    List<SuggestionCity> suggestionCities = result
                            .getSearchSuggestionCitys();// 当搜索不到poiitem数据时，会返回含有搜索关键字的城市信息
                    mList.clear();
                    if (poiItems != null && poiItems.size() > 0) {
                        getMapScreenShot();//截屏
                        mList.addAll(poiItems);
                    }  else {

                    }
                    adapter.notifyDataSetChanged();
                }
            } else {

            }
        } else {

        }
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {
        //System.out.print("返回：onPoiItemSearched\n");
        //System.out.print("位置："+poiItem.getAdName());
        //System.out.print("地址："+poiItem.getPoiExtension());
    }

    /**
     * 初始化
     */
    private void init() {
        if (aMap == null) {
            aMap = mapView.getMap();
            setUpMap();
        }

        //mLocationErrText = (TextView)findViewById(R.id.location_errInfo_text);
        //mLocationErrText.setVisibility(View.GONE);
    }

    /**
     * 设置一些amap的属性
     */
    private void setUpMap() {
        aMap.setLocationSource(this);// 设置定位监听
        aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        setupLocationStyle();
    }

    private void setupLocationStyle(){
        // 自定义系统定位蓝点
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        // 自定义定位蓝点图标
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.
                fromResource(R.drawable.gps_point));
        // 自定义精度范围的圆形边框颜色
        myLocationStyle.strokeColor(STROKE_COLOR);
        //自定义精度范围的圆形边框宽度
        myLocationStyle.strokeWidth(5);
        // 设置圆形的填充颜色
        myLocationStyle.radiusFillColor(FILL_COLOR);
        // 将自定义的 myLocationStyle 对象添加到地图上
        aMap.setMyLocationStyle(myLocationStyle);
    }
    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
        deactivate();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        if(null != mlocationClient){
            mlocationClient.onDestroy();
        }
    }

    /**
     * 定位成功后回调函数
     */
    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (mListener != null && amapLocation != null) {
            if (amapLocation != null
                    && amapLocation.getErrorCode() == 0) {
                mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
                aMap.moveCamera(CameraUpdateFactory.zoomTo(18));
                doSearch(amapLocation.getLongitude(),amapLocation.getLatitude(),amapLocation.getCity());
            } else {
                //String errText = "定位失败," + amapLocation.getErrorCode()+ ": " + amapLocation.getErrorInfo();
                //Log.e("AmapErr",errText);
                //mLocationErrText.setVisibility(View.VISIBLE);
                //mLocationErrText.setText(errText);
                if (isTip == false){
                    isTip = true;
                    ToastUtil.show(SearchLocationActivity.this, "亲，如遇到无法定位，请检查【微句】应用定位权限是否开启。");
                }
                goIntentSetting();

            }
        }
    }

    private void goIntentSetting() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", getPackageName(), null);
        intent.setData(uri);
        try {
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 激活定位
     */
    @Override
    public void activate(OnLocationChangedListener listener) {
        mListener = listener;
        if (mlocationClient == null) {
            mlocationClient = new AMapLocationClient(this);
            mLocationOption = new AMapLocationClientOption();
            //设置定位监听
            mlocationClient.setLocationListener(this);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mlocationClient.startLocation();
        }
    }

    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }

    //地图截屏
    private void getMapScreenShot(){
        aMap.getMapScreenShot(this);
        aMap.invalidate();// 刷新地图
    }

    @Override
    public void onMapScreenShot(Bitmap bitmap) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        if(null == bitmap){
            return;
        }
        try {
            filePath = CommonUtils.getFile(Environment.DIRECTORY_PICTURES) + "/test_"
                    + sdf.format(new Date()) + ".png";
            FileOutputStream fos = new FileOutputStream(
                    filePath);
            boolean b = bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            try {
                fos.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (b){
                System.out.print("截屏成功\n");
            } else {
                System.out.print("截屏失败\n");
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    private class MyAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return mList.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return mList.get(position);
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }
        @Override
        public boolean isEnabled(int position) {
            // TODO Auto-generated method stub
            return super.isEnabled(position);
        }

        /**
         * @param position
         * @param convertView
         * @param parent
         * @return
         */
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            View view=convertView;
            view= LayoutInflater.from(CustomApplication.mContext).inflate(R.layout.selectlocation_listview_item, null);
            TextView title = (TextView) view.findViewById(R.id.selectlocation_listview_item_title);
            TextView detail = (TextView) view.findViewById(R.id.selectlocation_listview_item_detail);
            PoiItem poiItem = mList.get(position);
            title.setText(CommonUtils.formatString(poiItem.getTitle()));
            detail.setText(CommonUtils.formatString(poiItem.getSnippet()));
            title.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
            detail.setTextColor(AppThemeUtils.getInstance().getLightTextColor());
            RelativeLayout selectlocation = (RelativeLayout) view.findViewById(R.id.selectlocation);
            selectlocation.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
            return view;
        }
    }

    public class Watcher implements TextWatcher
    {
        private EditText EditID = null;
        public Watcher(EditText id){
            EditID = id;
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // TODO Auto-generated method stub
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            // TODO Auto-generated method stub
        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub
            if (!CommonUtils.isEmpty(EditID.getText().toString())){
                System.out.print("开始搜索\n");
                query = new PoiSearch.Query(EditID.getText().toString(), "", "");
                //keyWord表示搜索字符串，
//第二个参数表示POI搜索类型，二者选填其一，
//POI搜索类型共分为以下20种：汽车服务|汽车销售|
//汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|医疗保健服务|
//住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|交通设施服务|
//金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施
//cityCode表示POI搜索区域，可以是城市编码也可以是城市名称，也可以传空字符串，空字符串代表全国在全国范围内进行搜索
                query.setPageSize(20);// 设置每页最多返回多少条poiitem
                query.setPageNum(0);//设置查询页码，从0开始
                poiSearch = new PoiSearch(SearchLocationActivity.this, query);
                poiSearch.setOnPoiSearchListener(SearchLocationActivity.this);
                poiSearch.searchPOIAsyn();
            }
        }

    }

}
